# -*- coding: utf-8 -*-

from rest_framework.decorators import action
from core.response import JsonResponse
from core.viewset import CustomModelViewSet
from django.http import FileResponse
from .models import Hawkeye
from .serializers import *
from .resources import *
from .filters import *
from apps.oms import tasks
from pathlib import Path
from application.settings import BASE_DIR


class HawkeyeViewSet(CustomModelViewSet):
    """
    鹰眼管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = Hawkeye.objects.all()
    serializer_class = HawkeyeSerializer
    filterset_class = HawkeyeFilterSet
    import_resources = HawkeyeResouces
    export_resources = HawkeyeResouces


class HawkeyeJobViewSet(CustomModelViewSet):
    """
    鹰眼任务管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = HawkeyeJob.objects.all()
    serializer_class = HawkeyeJobSerializer
    list_serializer_class = HawkeyeJobListSerializer
    filterset_class = HawkeyeJobFilterSet

    @action(detail=True, methods=["PUT"])
    def change_status(self, request, *args, **kwargs):
        """修改状态"""
        instance = HawkeyeJob.objects.filter(id=kwargs.get("pk")).first()
        if instance:
            instance.status = request.data["status"]
            instance.save()
            return JsonResponse(data={"status": instance.status}, msg="修改成功")
        else:
            return JsonResponse(msg="修改失败")

    @action(detail=False, methods=["PUT"])
    def start(self, request, *args, **kwargs):
        """
        开始执行任务
        """
        try:
            for data in request.data:
                HawkeyeJob.objects.filter(id=data).update(status='2')
                tasks.start(data, request.user.dept_belong_id)
            return JsonResponse(msg="执行成功")
        except Exception as ex:
            return JsonResponse(code=500, msg=f"执行失败：{str(ex)}")

    @action(detail=False, methods=["PUT"])
    def stop(self, request, *args, **kwargs):
        """
        停止执行任务
        """
        try:
            for data in request.data:
                tasks.stop(data)
                HawkeyeJob.objects.filter(id=data).update(status='7')
            return JsonResponse(msg="停止成功")
        except Exception as ex:
            return JsonResponse(code=500, msg=f"停止失败：{str(ex)}")


class HawkeyeJobPluginViewSet(CustomModelViewSet):
    """
    任务插件接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = HawkeyeJobPlugin.objects.all()
    serializer_class = HawkeyeJobPluginSerializer

    @action(detail=False, methods=["POST"])
    def download(self, request, pk=None, *args, **kwargs):
        file_name = request.data.get("file")
        file_path = BASE_DIR.joinpath(Path(file_name).relative_to("/"))
        response = FileResponse(open(file_path, "rb"))
        return response
